import 'package:badges/badges.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutterlib/common/net/dao_result.dart';
import 'package:flutterlib/common/style/font_awesome4_icons.dart';
import 'package:flutterlib/common/style/meterial_design_icons.dart';
import 'package:flutterlib/common/style/quhui_style.dart';
import 'package:flutterlib/common/utils/navigator_utils.dart';
import 'package:flutterlib/common/utils/utils.dart';
import 'package:flutterlib/model/app_version.dart';
import 'package:flutterlib/widgets/bussiness/user_info_widget.dart';
import 'package:flutterlib/widgets/pull/nested/simple_pull_load_manger.dart';
import 'package:flutterlib/widgets/pull/nested/simple_pull_load_page_widget.dart';
import 'package:flutterlib/common/constants/constants.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:share/share.dart';
import 'package:thrio/thrio.dart';

class NavList {
  NavList({
    this.navigateScreen,
    this.imagePath,
    this.name = '',
    this.thiroPath = '',
  });

  Widget navigateScreen;
  String name;
  IconData imagePath;
  String thiroPath;

  static List<NavList> homeList = [
    // NavList(
    //     imagePath: MIcon.message,
    //     name: "我的消息",
    //     thiroPath: '/native/ImPersonalMsgActivity'),
    NavList(
        imagePath: MIcon.group,
        name: "我的消息",
        thiroPath: '/native/ImCarrierActivity'),
    NavList(
        imagePath: MIcon.event_note,
        name: "我的待办",
        thiroPath: '/native/MyAllTodoActivity'),
    NavList(imagePath: AIcon.doc, name: "我的文章", thiroPath: '/post/mine'),
    NavList(
        imagePath: AIcon.picture, name: "我的趣图", thiroPath: '/post/cardmine'),
    NavList(
        imagePath: MIcon.directions_bike,
        name: "我的兴趣",
        thiroPath: '/interest/mine'),
    NavList(
        imagePath: MIcon.local_activity,
        name: "我的活动",
        thiroPath: '/activity/mine'),
    NavList(imagePath: MIcon.feedback, name: "意见反馈", thiroPath: '/post/report'),
    NavList(
        imagePath: AIcon.export_icon,
        name: "推荐好友",
        thiroPath: '/native/HtmlInviteActivity'),
    NavList(
        imagePath: AIcon.phone_1,
        name: "联系我们",
        thiroPath: '/native/ContactUsActivity'),
    NavList(
        imagePath: AIcon.phone_1, name: "管理员审核通道", thiroPath: '/post/admin'),
  ];
}

//我的页面
class Page extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return PageState();
  }
}

class PageState extends State<Page> with TickerProviderStateMixin {
  SimplePullLoadManger manger;
  final SettingsStore store =
      Provider.of<SettingsStore>(currentContext, listen: false);

  @override
  void initState() {
    super.initState();

    manger = SimplePullLoadManger(
        getDataLogic: getDataLogic,
        renderItem: renderItem,
        renderHeader: renderHeader,
        enablePullDown: false,
        enablePullUp: false);
  }

  getDataLogic(int page) async {
    print(page);

    return new DataResult(NavList.homeList, true);
  }

  Widget renderItem(index, tabItem) {
    // trueDebugPrint("fluttermsg mine page ${tabItem.name}");
    if (tabItem.name == "我的待办") {
      return Observer(builder: (_) {
        int todoCount = store.unReadTodoMsgCount;

        return getTabItem(tabItem, todoCount, () {
          if (currentUser == null) {
            NavigatorUtils.goLogin(context);
            return;
          }
          store.setUnReadTodoMsgCount(0);
          ThrioNavigator.push(url: tabItem.thiroPath);
        });
      });
    } else if (tabItem.name == "我的消息") {
      return Observer(builder: (_) {
        int ucgCount = store.unReadUCGMsgCount;
        int uuCount = store.unReadUUMsgCount;
        return getTabItem(tabItem, ucgCount + uuCount, () {
          if (currentUser == null) {
            NavigatorUtils.goLogin(context);
            return;
          }
          store.setUnReadUCGMsgCount(0);
          store.setUnReadUUMsgCount(0);
          ThrioNavigator.push(url: tabItem.thiroPath);
        });
      });
    } else if (tabItem.name == "管理员审核通道") {
      return Observer(builder: (_) {
        var userEntity = store.userEntity;
        if (userEntity == null || ![17, 19, 21].contains(userEntity.uid)) {
          return Container();
        } else {
          return getTabItem(tabItem, 0, () {
            ThrioNavigator.push(url: tabItem.thiroPath);
          });
        }
      });
    } else {
      return getTabItem(tabItem, 0, () {
        if (tabItem.name == "推荐好友") {
          _onShare(context);
          return;
        }
        if (tabItem.name == "联系我们") {
        } else {
          if (currentUser == null) {
            NavigatorUtils.goLogin(context);
            return;
          }
        }
        ThrioNavigator.push(url: tabItem.thiroPath);
      });
    }
  }

  _onShare(BuildContext context) async {
    // A builder is used to retrieve the context immediately
    // surrounding the RaisedButton.
    //
    // The context's `findRenderObject` returns the first
    // RenderObject in its descendent tree when it's not
    // a RenderObjectWidget. The RaisedButton's RenderObject
    // has its position and size after it's built.
    final RenderBox box = context.findRenderObject();
    // if (post.thumbnail.isNotEmpty) {
    //   await Share.shareFiles([post.thumbnail],
    //       text: post.title,
    //       subject: "趣会文章分享",
    //       sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size);
    // } else {
    AppVersion _lastAppVersion = appVersion;
    var shareText = "我在用趣会app，分享给你。下载地址${_lastAppVersion.url}";
    await Share.share(shareText,
        subject: "趣会app分享",
        sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size);
    // }
  }

  List<Widget> renderHeader(BuildContext context, bool innerBoxIsScrolled) {
    return <Widget>[
      SafeArea(
        child: Consumer<SettingsStore>(
          builder: (_, store, __) {
            return Observer(
              builder: (_) {
                final userEntity = store.userEntity;

                return Padding(
                  padding: const EdgeInsets.fromLTRB(15.0, 41, 0, 18.0),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      UserInfoWidget(
                          image: userEntity?.logo??'',
                          width: 60,
                          height: 60,
                          onPressed: () {
                            if (isLogin) {
                              ThrioNavigator.push(
                                  url: "/native/MineSettingActivity",
                                  poppedResult: (params) {
                                    trueDebugPrint(
                                        'flutterting /biz1/native1 poppedResult call params:$params');
                                    setState(() {});
                                  });
                            } else {
                              NavigatorUtils.goLogin(context);
                            }
                          }),
                      SizedBox(
                        width: 20.w,
                      ),
                      SizedBox(
                        width: 200,
                        height: 50,
                        child: InkWell(
                          onTap: () {
                            if (currentUser == null) {
                              NavigatorUtils.goLogin(context);
                            } else {
                              ThrioNavigator.push(
                                  url: "/native/MineSettingActivity",
                                  poppedResult: (params) {
                                    trueDebugPrint(
                                        'flutterting /biz1/native1 poppedResult call params:$params');
                                    setState(() {});
                                  });
                            }
                          },
                          child: Align(
                            alignment: Alignment.topLeft,
                            child: store.isLogin
                                ? Text(
                                    userEntity?.userName,
                                    style: QuhuiConstant.middleTextBold,
                                  )
                                : Text(
                                    "登录/注册",
                                    style: QuhuiConstant.middleTextBold,
                                  ),
                          ),
                        ),
                      ),
                    ],
                  ),
                );
              },
            );
          },
        ),
      ),
    ];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        title: Text(""),
        leading: Text(''),
        actions: [
          InkWell(
            onTap: () {
              ThrioNavigator.push(url: "/user/setting");
            },
            child: Icon(AIcon.cog),
          )
        ],
      ),
      backgroundColor: QuhuiColors.miWhite,
      body: SimplePullLoadWidget(
        pullLoadManger: manger,
      ),
    );
  }

  Widget getTabItem(NavList tabItem, int ucgCount, Function f) {
    // trueDebugPrint(
    //     "fluttermsg mine page gettabitem ${tabItem.name} ${ucgCount}");
    return ucgCount > 0
        ? Container(
            child: InkWell(
                splashColor: Colors.white.withOpacity(0.2),
                // highlightColor: Colors.transparent,
                // focusColor: Colors.transparent,
                onTap: () {
                  f?.call();
                  // NavigatorUtils.NavigatorRouter(context, tabItem.navigateScreen);
                },
                child: Padding(
                  padding: const EdgeInsets.fromLTRB(17.0, 17, 10, 17),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Icon(
                        tabItem.imagePath,
                        size: 14,
                      ),
                      SizedBox(
                        width: 12,
                      ),
                      Badge(
                        shape: BadgeShape.square,
                        borderRadius: BorderRadius.circular(5),
                        position: BadgePosition.topEnd(top: -10, end: -10),
                        padding: EdgeInsets.all(2),
                        badgeContent: Text(
                          '${ucgCount}',
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: 10,
                              fontWeight: FontWeight.bold),
                        ),
                        child: Text(
                          tabItem.name,
                          style: QuhuiConstant.minText,
                        ),
                      ),
                      Expanded(child: Container()),
                      Icon(
                        AIcon.right_open,
                        size: 12,
                      ),
                    ],
                  ),
                )))
        : Container(
            child: InkWell(
                splashColor: Colors.white.withOpacity(0.2),
                // highlightColor: Colors.transparent,
                // focusColor: Colors.transparent,
                onTap: () {
                  f?.call();
                  // NavigatorUtils.NavigatorRouter(context, tabItem.navigateScreen);
                },
                child: Padding(
                  padding: const EdgeInsets.fromLTRB(17.0, 17, 10, 17),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Icon(
                        tabItem.imagePath,
                        size: 14,
                      ),
                      SizedBox(
                        width: 12,
                      ),
                      Expanded(
                        child: Text(
                          tabItem.name,
                          style: QuhuiConstant.minText,
                        ),
                      ),
                      Icon(
                        AIcon.right_open,
                        size: 12,
                      )
                    ],
                  ),
                )));
  }
}
